import axios, { AxiosRequestConfig } from "axios"
import { Store } from "vuex";
import { State, Goods, PriceObject } from "../store/main"
import { USE_AJAX } from "../config"

export async function request<T = unknown>(config: AxiosRequestConfig) {
  const instance = axios.create({
    timeout: 5000
  });
  instance.interceptors.response.use(data => data.data, err => { (window as any).e = err;console.error(err);throw err })
  return (await instance(config)) as unknown as T
}
export function getJSON(store: Store<State>): void {

  if (!USE_AJAX) {
    setTimeout(() => store.commit("setGoods", [
      {
        "img-src": "http://img.product.it168.com/product/8583659.jpg_product-210x210",
        "title": "a",
        "price": 10,
        "body": "long long long long long long long long long long long long long long long description"
      },
      {
        "img-src": "http://img.product.it168.com/product/8583659.jpg_product-210x210",
        "title": "b",
        "price": 100,
        "body": "long long long long long long long long long long long long long long long description"
      },
      {
        "img-src": "http://img.product.it168.com/product/8583659.jpg_product-210x210",
        "title": "c",
        "price": 1000,
        "body": "long long long long long long long long long long long long long long long description"
      }
    ]), 250)
    return
  }
  if (store.state.goods.length !== 0) {
    return
  }
  const ret = request<Goods[]>({
    url: "/test.json",
    responseType: "json"
  })
  .then(a => {
    store.commit("setGoods", a)
  })
  .catch(console.error)
}

export function doCheckout(price: PriceObject, userId: number, loginToken: string) {
  type ResultType = {
    success: boolean,
    errCode: number | null
  }
  if (!USE_AJAX) {
    return new Promise<ResultType>(
      (resolve, reject) => setTimeout(() => resolve({
        success: true,
        errCode: null
      }), 500)
    )
  }
  return new Promise<ResultType>(async (resolve, reject) => {
    let priceMap = price.priceMap
    let goodsString = ""
    priceMap.forEach(function (value, key) {
      goodsString = goodsString.concat(key.toString(), ":", value.count.toString(), ",")
    })
    goodsString = goodsString.slice(0, goodsString.length - 1)
    resolve(await request<ResultType>({
      method: "POST",
      url: "/checkout",
      responseType: "json",
      params: {
        "user-id": userId,
        "login-token": loginToken,
        goods: goodsString
      }
    }))
  })
}


export interface LoginForm {
  userName: string,
  password: string
}

export async function submitLoginForm(store: Store<State>, submitObj: LoginForm) {
  const returnValue = await request<{
    success: boolean,
    userID: string | null,
    loginToken: string | null
  }>({
    method: "POST",
    url: "/login.json",
    responseType: "json",
    params: submitObj
  })
  if (!returnValue.success) {
    throw new Error("login failed")
  }
  store.commit("setLoginToken", returnValue.loginToken!)
  store.commit("setUserID", returnValue.userID!)
}